package com.furongji.education.utils;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.furongji.common.exception.MyException;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.Objects;

@Component
public class AliyunVodOperator {

    @Value("${aliyun.vod.accesskey_id}")
    private String accessKey_id;

    @Value("${aliyun.vod.accesskey_secret}")
    private String accessKey_secret;

    //读取AccessKey信息
    public DefaultAcsClient initVodClient() throws ClientException {
        String regionId = "cn-shanghai";  // 点播服务接入地域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, System.getenv(accessKey_id),
                System.getenv(accessKey_secret));
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient client) throws Exception {
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        request.setTitle("this is a sample");
        request.setFileName("filename.mp4");

        //UserData，用户自定义设置参数，用户需要单独回调URL及数据透传时设置(非必须)
        //JSONObject userData = new JSONObject();

        //UserData回调部分设置
        //消息回调设置，指定时以此为准，否则以全局设置的事件通知为准
        //JSONObject messageCallback = new JSONObject();
        //设置回调地址
        //messageCallback.put("CallbackURL", "http://192.168.0.1/16");
        //设置回调方式，默认为http
        //messageCallback.put("CallbackType", "http");
        //userData.put("MessageCallback", messageCallback.toJSONString());

        //UserData透传数据部分设置
        //用户自定义的扩展字段，用于回调时透传返回
        //JSONObject extend = new JSONObject();
        //extend.put("MyId", "user-defined-id");
        //userData.put("Extend", extend.toJSONString());

        //request.setUserData(userData.toJSONString());

        return client.getAcsResponse(request);
    }

    public String UploadVideo(MultipartFile file) throws Exception {
        String title = Objects.requireNonNull(file.getOriginalFilename()).substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        UploadStreamRequest request = new UploadStreamRequest(accessKey_id, accessKey_secret, title, fileName, inputStream);
        UploadVideoImpl uploader = new UploadVideoImpl();
        request.setApiRegionId("cn-beijing");
        request.setStorageLocation("outin-dc1ef2be371211f0846300163e086cc1.oss-cn-beijing.aliyuncs.com");

        UploadStreamResponse response = uploader.uploadStream(request);
        System.out.print("RequestId=" + response.getRequestId() + "\n"); //请求视频点播服务的请求ID
        if (response.isSuccess()) {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
        } else {
            System.out.print("VideoId=" + response.getVideoId() + "\n");
            System.out.print("ErrorCode=" + response.getCode() + "\n");
            System.out.print("ErrorMessage=" + response.getMessage() + "\n");
        }
        return response.getVideoId();
    }


    public String getVideoAuth(String videoId) {

        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing", accessKey_id, accessKey_secret);

        IAcsClient client = new DefaultAcsClient(profile);

        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);
        GetVideoPlayAuthResponse response = null;

        try {
            response = client.getAcsResponse(request);
            return response.getPlayAuth();
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyException(20001, "获取视频播放凭证失败");
        }
    }

    public void removeVideo(String id) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing",
                accessKey_id, accessKey_secret);

        IAcsClient client = new DefaultAcsClient(profile);

        DeleteVideoRequest request = new DeleteVideoRequest();
        request.setVideoIds(id);

        try {
            DeleteVideoResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }

    public void removeVideoList(List<String> videoIdList) {
        System.err.println("edu-vod:" + videoIdList);
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing",
                accessKey_id, accessKey_secret);

        IAcsClient client = new DefaultAcsClient(profile);
        DeleteVideoRequest request = new DeleteVideoRequest();

        String videoIds = StringUtils.join(videoIdList.toArray(), ",");
        request.setVideoIds(videoIds);

        try {
            DeleteVideoResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
    }
}
